package www.m01.springcloud.controller;

import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import www.m01.springcloud.domains.Payment;
import www.m01.springcloud.domains.Rs;
import www.m01.springcloud.service.PaymentService;

/**
 * PaymentController
 *
 * @author hyr
 * @date 2022/7/8
 */
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private Integer serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public Rs<Integer> create(@RequestBody Payment payment) {
        int i = paymentService.create(payment);
        if (i == 1) {
            return new Rs<>(Rs.SUCCESS, "success", i);
        } else {
            return new Rs<>(Rs.FAILED, "failed", i);
        }
    }

    @GetMapping("get/{id}")
    public Rs<Payment> getPayment(@PathVariable("id") Long id) {
        Payment pa = paymentService.getPaymentById(id);
        if (pa == null) {
            return new Rs<>(Rs.FAILED, "不存在", null);
        } else {
            return new Rs<>(Rs.SUCCESS, "success : " + serverPort , pa);
        }
    }

    @GetMapping("/discovery")
    public Object getDiscovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(s);
            log.info("service : {}, instances : {}", s, instances);
        });
        return discoveryClient;
    }

}
